<?php

/**
 * 请求缓存类
 * @author bing.peng
 *
 */
class Cache {

	var $cache_path;
	
	function Cache() {
		$this->cache_path = TATUPATH . '/cache/';
	}
	
	/**
	 * 根据请求的URL读取缓存
	 * 如果请求的URL没有缓存，返回FALSE
	 * 如果请求的URL缓存过期，则删除缓存文件，再返回FALSE
	 * @param $url string 请求的URL
	 * @return string/FALSE
	 */
	function get($url) {
		$filename = $this->cache_path . md5($url);
		if( file_exists($filename) ) {
			$content = $this->safe_file_get_contents($filename);
			$tmp = explode('<<%-==-%>>', $content);  
            $timeout = $tmp[0];  
            $value = $tmp[1];  
            if ( time() > $timeout) {  
            	unlink($filename);
                return FALSE;  
            } else {  
                return $value;  
            }
		}
		else {
			return FALSE;
		}
	} 
	
	/**
	 * 缓存请求响应
	 * @param $url string 请求的URL
	 * @param $content string 要保存的内容
	 * @param $expire int 缓存保存的时间
	 * @return bool
	 */
	function set($url, $content, $expire = 36000) {
		$filename = $this->cache_path . md5($url);
		$timeout = time() + $expire;
		return $this->safe_file_put_contents($filename, $timeout . '<<%-==-%>>' . $content);
	}
	
	/**
	 * 刷新缓存
	 * @return bool
	 */
	function flash() {
		return unlink($filename); 
	}
	
	function safe_file_put_contents($filename, $content) {  
        $fp = fopen($filename, 'wb');  
        if ($fp) {  
            flock($fp, LOCK_EX);  
            fwrite($fp, $content);  
            flock($fp, LOCK_UN);  
            fclose($fp);  
            return true;  
        } else {  
            return false;  
        }  
    }
    
	function safe_file_get_contents($filename) {  
        $fp = fopen($filename, 'rb');  
        if ($fp) {  
            flock($fp, LOCK_SH);  
            clearstatcache();  
            $filesize = filesize($filename);  
            if ($filesize > 0) {  
                $data = fread($fp, $filesize);  
            }  
            flock($fp, LOCK_UN);  
            fclose($fp);  
            return $data;  
        } else {  
            return false;  
        }  
    }
    
}

?>